import {
  Body,
  Controller,
  Delete,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Patch,
  Post,
  Query,
  Req,
} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { JwtNeed } from '@/common/decorator'
import { PlayerUserService } from '../user/player-user.service'
import {
  CreateQuestionRecordDto,
  ListPageQuestionRecordDto,
  ListPageQuestionRecordVo,
} from './dto/question-record.dto'
import {
  CreateQuestionDto,
  EnableQuestionDto,
  ListPageQuestionDto,
  ListPageQuestionVo,
  UpdateQuestionDto,
} from './dto/question.dto'
import { QuestionRecordService, QuestionService } from './question.service'

@ApiTags('后台/二期/问卷管理')
@Controller('admin/question')
export class QuestionController {
  constructor(
    private readonly service: QuestionService,
    private readonly questionRecordService: QuestionRecordService,
  ) {}

  /**
   * 获取问卷提交记录
   */
  @Get('record')
  record(@Query() query: ListPageQuestionRecordDto): Promise<ListPageQuestionRecordVo> {
    const { pageNo = 1, pageSize = 10, ...rest } = query
    return this.questionRecordService.findPage({ where: rest, relations: ['question'], pageNo, pageSize })
  }

  /**
   * 获取问卷列表
   */
  @Get()
  page(
    @Query()
    query: ListPageQuestionDto,
  ): Promise<ListPageQuestionVo> {
    const { pageNo = 1, pageSize = 10, ...rest } = query
    return this.service.findPage({ where: rest, pageNo, pageSize })
  }

  /**
   * 创建问卷
   */
  @Post()
  create(@Body() data: CreateQuestionDto) {
    if (data.isEnabled) {
      this.service.closeOtherEnabled()
    }
    return this.service.save(data)
  }

  /**
   * 修改问卷状态
   */
  @Post('/enable')
  async enable(@Body() data: EnableQuestionDto) {
    const response = await this.service.findOne({
      where: {
        questionId: data.questionId,
      },
    })

    if (!response) {
      throw new HttpException('问卷不存在', HttpStatus.NOT_FOUND)
    }

    if (response.isEnabled) {
      this.service.closeOtherEnabled()
    }

    return this.service.update(data.questionId, {
      isEnabled: !response.isEnabled,
    })
  }

  /**
   * 修改问卷
   */
  @Patch(':questionId')
  update(@Param('questionId') id: number, @Body() data: UpdateQuestionDto) {
    // 其他的全部设为不启用
    if (data.isEnabled) {
      this.service.closeOtherEnabled()
    }
    return this.service.update(id, data)
  }

  /**
   * 删除问卷
   */
  @Delete(':id')
  delete(@Param('id') id: number) {
    return this.service.delete(id)
  }
}

@ApiTags('官网/二期/问卷')
@Controller('web/question')
export class WebQuestionController {
  constructor(
    private readonly questionService: QuestionService,
    private readonly questionRecordService: QuestionRecordService,
    private readonly playerUserService: PlayerUserService,
  ) {}

  /**
   * 获取启用的问卷
   */
  @Get()
  list() {
    return this.questionService.findOne({
      where: {
        isEnabled: true,
      },
    })
  }

  /**
   * 提交问卷
   */
  @Post()
  @JwtNeed()
  async create(@Req() req: Request, @Body() data: CreateQuestionRecordDto) {
    if (!req.user.playerUserId) {
      throw new HttpException('玩家不存在', HttpStatus.BAD_REQUEST)
    }

    // 创建问卷记录
    const response = await this.questionRecordService.save({
      ...data,
      userUid: req.user.uid,
    })

    const playerUser = await this.playerUserService.findOne({
      where: {
        uid: req.user.uid,
      },
    })

    if (!playerUser) {
      throw new HttpException('玩家不存在', HttpStatus.BAD_REQUEST)
    }

    // 更新玩家评分(取最高)
    await this.playerUserService.update(playerUser.playerUserId, {
      questionScore: Math.max(playerUser.questionScore, response.totalScore),
    })
  }
}
